<template>
  <div class="order-list-container container">
    <div class="page-title">
      <h2>我的订单</h2>
    </div>
    
    <div class="filter-section card">
      <el-form :model="searchForm" :inline="true" size="small">
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="订单状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="待支付" value="1"></el-option>
            <el-option label="已支付" value="2"></el-option>
            <el-option label="已取消" value="3"></el-option>
            <el-option label="已完成" value="4"></el-option>
            <el-option label="已取车" value="5"></el-option>
            <el-option label="已还车" value="6"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="订单编号"></el-input>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="order-list card" v-loading="loading">
      <el-table :data="orderList" style="width: 100%">
        <el-table-column prop="orderNo" label="订单编号" width="180"></el-table-column>
        <el-table-column prop="vehicleName" label="车辆名称" width="180"></el-table-column>
        <el-table-column label="下单时间" width="160">
          <template slot-scope="scope">
            {{ scope.row.orderTime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template slot-scope="scope">
            <span class="amount">¥{{ scope.row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="viewDetail(scope.row.orderNo)">查看详情</el-button>
            <el-button 
              size="mini" 
              type="primary" 
              v-if="scope.row.status === 1"
              @click="handlePay(scope.row.orderNo)"
            >去支付</el-button>
            <el-button 
              size="mini" 
              type="danger" 
              v-if="scope.row.status === 1"
              @click="handleCancel(scope.row.orderNo)"
            >取消订单</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 空状态 -->
      <el-empty v-if="orderList.length === 0 && !loading" description="暂无订单数据"></el-empty>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageParams.current"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getMyOrders, cancelOrder } from '@/api/order'
import { parseTime } from '@/utils'

export default {
  name: 'OrderList',
  filters: {
    formatDate(time) {
      if (!time) return '暂无数据';
      // 尝试不同的方式解析日期
      try {
        // 如果是ISO格式字符串，直接解析
        if (typeof time === 'string') {
          return parseTime(new Date(time), '{y}-{m}-{d} {h}:{i}:{s}');
        }
        // 如果是Date对象
        return parseTime(time, '{y}-{m}-{d} {h}:{i}:{s}');
      } catch (error) {
        console.error('日期格式化错误:', error, time);
        return '格式错误';
      }
    }
  },
  data() {
    return {
      searchForm: {
        status: '',
        orderNo: '',
        dateRange: []
      },
      pageParams: {
        current: 1,
        size: 10
      },
      orderList: [],
      total: 0,
      loading: false
    }
  },
  created() {
    this.fetchOrderList()
  },
  methods: {
    fetchOrderList() {
      this.loading = true
      
      // 构造查询参数
      const queryParams = {
        pageNum: this.pageParams.current,
        pageSize: this.pageParams.size,
        orderNo: this.searchForm.orderNo,
        status: this.searchForm.status
      }
      
      // 添加日期范围参数
      if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
        queryParams.startTime = this.searchForm.dateRange[0] + ' 00:00:00'
        queryParams.endTime = this.searchForm.dateRange[1] + ' 23:59:59'
      }
      
      // 调用API获取订单列表
      getMyOrders(queryParams)
        .then(response => {
          if (response.code === 200) {
            this.orderList = response.data.records || []
            // 处理日期字段
            this.orderList.forEach(order => {
              if (order.orderTime) {
                try {
                  // 尝试将字符串转换为日期对象
                  order.orderTime = new Date(order.orderTime);
                } catch (error) {
                  console.error('日期转换错误:', error, order.orderTime);
                  order.orderTime = null;
                }
              }
            });
            this.total = response.data.total || 0
          } else {
            this.$message.error(response.message || '获取订单列表失败')
            this.orderList = []
            this.total = 0
          }
        })
        .catch(error => {
          console.error('获取订单列表失败', error)
          this.$message.error('获取订单列表失败，请检查网络连接')
          this.orderList = []
          this.total = 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSearch() {
      this.pageParams.current = 1
      this.fetchOrderList()
    },
    resetSearch() {
      this.searchForm = {
        status: '',
        orderNo: '',
        dateRange: []
      }
      this.pageParams.current = 1
      this.fetchOrderList()
    },
    handleSizeChange(size) {
      this.pageParams.size = size
      this.fetchOrderList()
    },
    handleCurrentChange(current) {
      this.pageParams.current = current
      this.fetchOrderList()
    },
    viewDetail(orderNo) {
      this.$router.push(`/order/detail/${orderNo}`)
    },
    handlePay(orderNo) {
      this.$router.push(`/order/payment/${orderNo}`)
    },
    handleCancel(orderNo) {
      this.$confirm('确定要取消该订单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用取消订单API
        cancelOrder(orderNo)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('订单取消成功')
              this.fetchOrderList() // 刷新订单列表
            } else {
              this.$message.error(response.message || '订单取消失败')
            }
          })
          .catch(error => {
            console.error('取消订单失败', error)
            this.$message.error('取消订单失败，请稍后重试')
          })
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },
    getStatusText(status) {
      const statusMap = {
        1: '待支付',
        2: '已支付',
        3: '已取消',
        4: '已完成',
        5: '已取车',
        6: '已还车'
      }
      return statusMap[status] || '未知状态'
    },
    getStatusType(status) {
      const typeMap = {
        1: 'warning',
        2: 'primary',
        3: 'danger',
        4: 'success',
        5: 'info',
        6: 'success'
      }
      return typeMap[status] || ''
    }
  }
}
</script>

<style lang="scss" scoped>
.order-list-container {
  padding: 20px 0;
  
  .page-title {
    margin-bottom: 20px;
    
    h2 {
      font-size: 24px;
      font-weight: 500;
      color: #303133;
      margin: 0;
    }
  }
  
  .filter-section {
    margin-bottom: 20px;
    padding: 20px;
  }
  
  .order-list {
    padding: 20px;
    
    .amount {
      color: #f56c6c;
      font-weight: bold;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  .card {
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}
</style> 